/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package DS;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.handler.MessageContext;

/**
 *
 * @author oana.leva
 */
@WebService(name  = "ChatService", serviceName="ChatWebService")
public class ChatService {
    
    Connection connection = null;
    private @Resource WebServiceContext webServiceContext;
    private HttpSession session;

    public ChatService()
    {
        initializeJdbc();  
    }

    @WebMethod(operationName="login")
    public boolean Login(String user, String password)
    {
        try
        {
            PreparedStatement userSetActive = connection.prepareStatement("update user set active=true where name=? and password = ?;");
            userSetActive.setString(1, user);
            userSetActive.setString(2, password);
            
            MessageContext messageContext =  webServiceContext.getMessageContext();
            session = ((HttpServletRequest)messageContext.get(MessageContext.SERVLET_REQUEST)).getSession();
            session.setAttribute("userName", user);

            if (userSetActive.executeUpdate()>0)
                return true;
            return false;
        }
        catch (SQLException ex) {
            Logger.getLogger(ChatService.class.getName()).log(Level.SEVERE, null, ex);
        }
        return false;
    }

    @WebMethod(operationName="signup")
    public void SignUp(String user, String password, String details)
    {
        try {
            PreparedStatement addUser = connection.prepareStatement("insert into user(name,password,details) values(?,?,?);");
            addUser.setString(1, user);
            addUser.setString(2, password);
            addUser.setString(3, details);
            addUser.executeUpdate();
        } catch (SQLException ex) {
            Logger.getLogger(ChatService.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @WebMethod(operationName="getStringUsers")
    public List<String> GetActiveStringUsers()
    {
        List<String> users = new ArrayList<String>();
        try {
            PreparedStatement statement1 = connection.prepareStatement("select * from user;");
            ResultSet resultSet = statement1.executeQuery();
            while (resultSet.next()) {
                if ((resultSet.getBoolean("active") == true))
                {
                    String user = resultSet.getString("name");
                    users.add(user);
                }
            }
        } catch (SQLException ex) {
            Logger.getLogger(ChatService.class.getName()).log(Level.SEVERE, null, ex);
        }
        return users;
    }

    @WebMethod(operationName="getStringChatrooms")
    public List<String> GetStringChatrooms()
    {
        List<String> chatrooms = new ArrayList<String>();
        try {
            PreparedStatement statement1 = connection.prepareStatement("select * from chatroom;");
            ResultSet resultSet = statement1.executeQuery();
            while (resultSet.next()) {
                    String chatroom = resultSet.getString("name");
                    chatrooms.add(chatroom);
            }
        } catch (SQLException ex) {
            Logger.getLogger(ChatService.class.getName()).log(Level.SEVERE, null, ex);
        }
        return chatrooms;
    }
    
    @WebMethod(operationName="getUsers")
    public List<User> GetActiveUsers()
    {
        List<User> users = new ArrayList<User>();
        try {
            PreparedStatement statement1 = connection.prepareStatement("select * from user;");
            ResultSet resultSet = statement1.executeQuery();
            if (resultSet.next()) {
                while ((resultSet.getBoolean("active") == true)  && (resultSet.getString("name")!= session.getAttribute("userName").toString()))
                {
                    User user = new User();
                    user.setName(resultSet.getString("name"));
                    user.setPassword(resultSet.getString("password"));
                    user.setDetails(resultSet.getString("details"));
                    users.add(user);
                }
            }
        } catch (SQLException ex) {
            Logger.getLogger(ChatService.class.getName()).log(Level.SEVERE, null, ex);
        }
        return users;
    }

    private int GetIdUser(String name)
    {
        try {
            PreparedStatement getID = connection.prepareStatement("select * from user where name=?;");
            getID.setString(1, name);

            ResultSet resultSet = getID.executeQuery();
            if (resultSet.next())
            {
                return Integer.parseInt(resultSet.getString("ID"));
            }

        } catch (SQLException ex) {
            Logger.getLogger(ChatService.class.getName()).log(Level.SEVERE, null, ex);
        }
        return 0;
    }

    private int GetIdLastChatroom()
    {
        try {
            PreparedStatement getID = connection.prepareStatement("select * from chatroom order by ID desc limit 1;");

            ResultSet resultSet = getID.executeQuery();
            if (resultSet.next())
            {
                return Integer.parseInt(resultSet.getString("ID"));
            }

        } catch (SQLException ex) {
            Logger.getLogger(ChatService.class.getName()).log(Level.SEVERE, null, ex);
        }
        return 0;
    }

    @WebMethod(operationName="startChatroom")
    public void StartChatroom(String endUser)
    {
        int startUserId = GetIdUser(session.getAttribute("userName").toString());
        int endUserId = GetIdUser(endUser);
        //--insert into chatroom----
        try 
        {
            PreparedStatement insertChatroom = connection.prepareStatement("insert into chatroom(private,name) values (?,?);");
            insertChatroom.setInt(1, 1);
            insertChatroom.setString(2, "chatroom_"+startUserId+"_"+endUserId);
            insertChatroom.execute();

        } catch (SQLException ex) {
            Logger.getLogger(ChatService.class.getName()).log(Level.SEVERE, null, ex);
        }

        int chatroomID = GetIdLastChatroom();
        session.setAttribute("chatroomID", chatroomID);

        //--insert into chatroom_user -->startuser
        try
        {
            PreparedStatement ins = connection.prepareCall("insert into chatroom_user(chatroom_id,user_id) values(?,?);");
            ins.setInt(1, chatroomID);
            ins.setInt(2, startUserId);

            ins.execute();
        }
        catch (SQLException ex) {
            Logger.getLogger(ChatService.class.getName()).log(Level.SEVERE, null, ex);
        }

        //--insert into chatroom_user -->enduser
        try
        {
            PreparedStatement ins = connection.prepareCall("insert into chatroom_user(chatroom_id,user_id) values(?,?);");
            ins.setInt(1, chatroomID);
            ins.setInt(2, endUserId);

            ins.execute();
        }
        catch (SQLException ex) {
            Logger.getLogger(ChatService.class.getName()).log(Level.SEVERE, null, ex);
        }

        
    }

    @WebMethod(operationName="writeMessage")
    public void WriteMessage(String text)
    {
        try {
            PreparedStatement writeMess = connection.prepareStatement("insert into message(text,senderID,chatroomID) values(?,?,?);");
            writeMess.setString(1, text);
            int chatroomID = Integer.parseInt(session.getAttribute("chatroomID").toString());
            int userID = GetIdUser(session.getAttribute("userName").toString());
            writeMess.setInt(2, userID);
            writeMess.setInt(3, chatroomID);

            writeMess.execute();

        } catch (SQLException ex) {
            Logger.getLogger(ChatService.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    private int GetIDChatroom(String chatroom)
    {
         try {
            PreparedStatement getID = connection.prepareStatement("select * from chatroom where name=?;");
            getID.setString(1, chatroom);

            ResultSet resultSet = getID.executeQuery();
            if (resultSet.next())
            {
                return Integer.parseInt(resultSet.getString("ID"));
            }

        } catch (SQLException ex) {
            Logger.getLogger(ChatService.class.getName()).log(Level.SEVERE, null, ex);
        }
        return 0;
    }

    @WebMethod(operationName="joinChatroom")
    public void JoinChatroom(String chatroomName)
    {
        int chatroomID = GetIDChatroom(chatroomName);
        int userId = GetIdUser(session.getAttribute("userName").toString());

        session.setAttribute("chatroomID", chatroomID);

        //--insert into chatroom_user--
        try
        {
            PreparedStatement ins = connection.prepareCall("insert into chatroom_user(chatroom_id,user_id) values(?,?);");
            ins.setInt(1, chatroomID);
            ins.setInt(2, userId);

            ins.execute();
        }
        catch (SQLException ex) {
            Logger.getLogger(ChatService.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private String GetNameUser(int userID)
    {
        try {
            PreparedStatement getID = connection.prepareStatement("select * from user where id=?;");
            getID.setInt(1, userID);

            ResultSet resultSet = getID.executeQuery();
            if (resultSet.next())
            {
                return resultSet.getString("name");
            }

        } catch (SQLException ex) {
            Logger.getLogger(ChatService.class.getName()).log(Level.SEVERE, null, ex);
        }
        return "";
    }

    @WebMethod(operationName="readMessage")
    public List<Message> ReadMessage()
    {
        int chatroomID = Integer.parseInt(session.getAttribute("chatroomID").toString());
        List<Message> msg = new ArrayList<Message>();

        try {
            PreparedStatement getID = connection.prepareStatement("select * from message where chatroomid=?;");
            getID.setInt(1, chatroomID);

            ResultSet resultSet = getID.executeQuery();
            while (resultSet.next())
            {
                Message message = new Message();
                message.setText(resultSet.getString("text"));
                message.setSender(GetNameUser(resultSet.getInt("senderid")));

                msg.add(message);
            }

        } catch (SQLException ex) {
            Logger.getLogger(ChatService.class.getName()).log(Level.SEVERE, null, ex);
        }
        return msg;
    }


    private void initializeJdbc() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://localhost:33067/chat", "root", "ltschat");
        }
        catch(Exception ex)
        {ex.printStackTrace();}
    }

}
